﻿#region Copyright(c) 2006 ZO, All right reserved.
// -----------------------------------------------------------------------------
// Copyright(c) 2006 ZO, All right reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   1.  Redistribution of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//   2.  Redistribution in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//   3.  The name of the author may not be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -----------------------------------------------------------------------------
#endregion


#region Using directives

using System;
using System.Globalization;
using System.Text;
using ZO.SmartCore.Core;
using ZO.SmartCore.Plugins.Properties;
using ZO.SmartCore.Reflection;
using ZO.SmartCore.Xml;
using ArgumentException= ZO.SmartCore.Core.ArgumentException;
using ArgumentNullException= ZO.SmartCore.Core.ArgumentNullException;
using Version= ZO.SmartCore.Core.Version;

#endregion

namespace ZO.SmartCore.Plugins
{
    /// <summary>
    /// Represents an plugin.
    /// </summary>
    [Serializable()]
	public sealed class Plugin : DisposableObject
    {

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="Plugin"/> class.
        /// </summary>
        /// <param name="type">The type.</param>
        internal Plugin(Type type)
        {
            if (!IsPlugin(type))
            {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, Resources.Arg_InvalidPluginType, new string[] { type.FullName }), "type");
            }
            this.type = type;

            GetInfo();
        }

		/// <summary>
		/// Initializes a new instance of the <see cref="Plugin"/> class.
		/// </summary>
		/// <param name="type">The type.</param>
		internal Plugin(TypeLoader type)
		{
			if (!IsPlugin(type))
			{
				throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, Resources.Arg_InvalidPluginType, new string[] { type.FullName }), "type");
			}
			this.newAppDomain = true;

			this.loaderType = type;

			GetInfo();
		}

        #endregion

        #region Destructor

        #endregion

        #region Fields
        private bool newAppDomain;

        private string _Name;

        private Guid _ID;

        private PluginImage _Image;

        private string _UpdateText;
        private string _Title;
        private string _Description;
        private DateTime _StartDate;
        private DateTime _ExpirationDate;
        private bool _Expires;
        private string _Trademark;
        private string _Copyright;
        private Uri _UpdateUrl;
        private Version _Version;

        private TypeLoader loaderType;

        private Type type;

        private PluginAssembly _Assembly;

        #endregion

        #region Events

        #endregion

        #region Operators

        #endregion

        #region Properties

	

        /// <summary>
        /// Returns the name of this plugin.
        /// </summary>
        public string Name
        {
            get
            {
                return this._Name;
            } // get
        } // Name


        /// <summary>
        /// Returns the ID of this plugin.
        /// </summary>
        public Guid ID
        {
            get
            {
                return this._ID;
            } // get
        } // ID

        /// <summary>
        /// Gets the image that will be displayed in the About dialog. 
        /// </summary>
        public PluginImage Image
        {
            get
            {
                return this._Image;
            } // get
        } // Image

        /// <summary>
        /// this info is used if Application want to show info about updating assembly
        /// </summary>
        /// <value>URL Update Text</value>
        public string UpdateText
        {
            get
            {
                return this._UpdateText;
            } // get
        } // UpdateText

        /// <summary>
        /// Gets the title of the plugin module displayed in the About dialog. 
        /// </summary>
        public string Title
        {
            get
            {
                return this._Title;
            } // get
        } // Title

        /// <summary>
        /// A short description of this plugin.  
        /// </summary>
        public string Description
        {
            get
            {
                return this._Description;
            } // get
        } // Description

        /// <summary>
        /// Get the starting date of this plugin's operating window if it expires
        /// </summary>
        public DateTime StartDate
        {
            get
            {
                return this._StartDate;
            } // get
        } // StartDate

        /// <summary>
        /// Get the expiration date of this plugin's operating window if it expires
        /// </summary>
        public DateTime ExpirationDate
        {
            get
            {
                return this._ExpirationDate;
            } // get
        } // ExpirationDate

        /// <summary>
        /// Gets whether this plugin expires.. 
        /// </summary>
        public bool Expires
        {
            get
            {
                return this._Expires;
            } // get
        } // Expires

        /// <summary>
        /// Gets the plugin trademark. 
        /// </summary>
        public string Trademark
        {
            get
            {
                return this._Trademark;
            } // get
        } // Trademark

        /// <summary>
        /// Gets the plugin copyright. 
        /// </summary>
        public string Copyright
        {
            get
            {
                return this._Copyright;
            } // get
        } // Copyright

        /// <summary>
        /// URL to which request is forward for new version
        /// </summary>
        /// <value>URL to Update Assembly</value>
        public Uri UpdateUrl
        {
            get
            {
                return this._UpdateUrl;
            } // get
        } // UpdateURL

        /// <summary>
        /// Get the version of this product.
        /// </summary>
        /// <value>Plugin Version</value>
        public Version Version
        {
            get
            {
                return this._Version;
            } // get
        }

        /// <summary>
        /// Gets the plugin base interface.
        /// </summary>
        /// <returns></returns>
        public IPluginInfo PluginInfo
        {
            get
            {
                IPluginInfo obj;

                try
                {
                    if (newAppDomain)
                    {
                        obj = this.loaderType.CreateModule() as IPluginInfo;
                    }
                    else
                    {
                        obj = Activator.CreateInstance(this.type) as IPluginInfo;
                    }
                }catch(Exception)
                {
                    obj = null;
                }

                return obj;
            }
        } // PluginInfo
        #endregion

        #region Methods

        /// <summary>
        /// Determines whether the specified type is plugin.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>
        /// 	<c>true</c> if the specified type is plugin; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsPlugin(TypeLoader type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            } // if

            if (type.IsDefined(typeof(PluginAttribute), false))
            {
                return true;
            }
            return false;

        }

        /// <summary>
        /// Determines whether the specified type is plugin.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>
        /// 	<c>true</c> if the specified type is plugin; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsPlugin(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            } // if

            if (type.IsDefined(typeof(PluginAttribute), false))
            {
                return true;
            }
            return false;

        }



        /// <summary>
        /// Determines whether the plugin of specified type.
        /// </summary>
        /// <param name="pluginInterfaceType">The type.</param>
        /// <returns>
        /// 	<c>true</c> if the plugin is of specified type; otherwise, <c>false</c>.
        /// </returns>     
        public bool IsPluginOfType(Type pluginInterfaceType)
        {
            if (pluginInterfaceType == null)
            {
                throw new ArgumentNullException("pluginInterfaceType");
            }

            if (newAppDomain)
            {
                return this.loaderType.IsAssignableTo(pluginInterfaceType);
            }
            return (pluginInterfaceType.IsAssignableFrom(this.type));

        }

        /// <summary>
        /// Gets the plugin base interface.
        /// </summary>
        /// <returns></returns>
        public Object GetPluginInterface()
        {
            Object obj;

            try
            {
                if (newAppDomain)
                {
                    obj = this.loaderType.CreateModule(); ;
                } // if
                else
                {
                    obj = Activator.CreateInstance(this.type);
                } // else
            }
            catch (Exception)
            {
                obj = null;
            }

            return obj;

        } // GetPluginInterface

        /// <summary>
        /// Gets the assembly in from which this plugin is loaded.
        /// </summary>
        /// <value>The assembly.</value>
        public PluginAssembly Assembly
        {
            get
            {
                return _Assembly;
            } // get
            internal set
            {
                _Assembly = value;
            } // set
        } // Assembly


        private void GetInfo()
        {
            IPluginInfo info = this.PluginInfo;

            if (info != null)
            {
                this._Name = info.Name;
                this._ID = info.ID;
                this._Image = info.Image;
                this._Copyright = info.Copyright;
                this._Description = info.Description;
                this._ExpirationDate = info.ExpirationDate;
                this._Expires = info.Expires;
                this._StartDate = info.StartDate;
                this._Title = info.Title;
                this._Trademark = info.Trademark;
                this._UpdateText = info.UpdateText;
                this._UpdateUrl = info.UpdateUrl;
                this._Version = info.Version;
            }
        }

        /// <summary>
        /// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
        /// </returns>
        public override string ToString()
        {
            Element pluginElement = new Element("plugin");
            pluginElement.Attributes.Add("name", this.Name);
            pluginElement.AddChildElement("id", this.ID.ToString());

            if (this.Image != null)
            {
                Element imageElement = pluginElement.AddChildElement("image");
                byte[] buffer = this.Image.GetBytes();

                StringBuilder sb = new StringBuilder(buffer.Length);
                for (int i = 0; i < buffer.Length; i++)
                {
                    sb.Append(buffer[i].ToString());
                }

                imageElement.Value = sb.ToString();
            }

            pluginElement.AddChildElement("copyright", this.Copyright);
            pluginElement.AddChildElement("description", this.Description);
            pluginElement.AddChildElement("expirationdate", this.ExpirationDate.ToString());
            pluginElement.AddChildElement("expires", this.Expires.ToString());
            pluginElement.AddChildElement("startdate", this.StartDate.ToString());
            pluginElement.AddChildElement("title", this.Title.ToString());
            pluginElement.AddChildElement("trademark", this.Trademark);
            pluginElement.AddChildElement("updatetext", this.UpdateText);
            if (this.UpdateUrl != null)
            {
                pluginElement.AddChildElement("updateurl", this.UpdateUrl.ToString());
            }
            pluginElement.AddChildElement("version", this.Version.ToString());
            return pluginElement.ToString();
        }
  
        /// <summary>
        /// Override This Method To Dispose Unmanaged Resources.
        /// </summary>
        protected override void DisposeManagedResources()
        {
            this._Assembly = null;
            this.type = null;

			if (loaderType != null)
			{
				this.loaderType.Dispose();
				this.loaderType = null;

			}
        }   

        #endregion
    }
}
